/**
 * Jul 11, 2012
 */
package ee.tallink.common.db;

import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.SQLException;

import org.javalite.activejdbc.Base;
import org.javalite.activejdbc.LazyList;
import org.javalite.activejdbc.MetaModel;
import org.javalite.activejdbc.Model;
import org.javalite.activejdbc.Registry;
import org.javalite.common.Convert;

import ee.tallink.common.db.TLazyList;

/**
 * @author andrei
 *
 */
public class DataBase {
	static String TLNK_DB_JNDI_NAME = "java:comp/env/jdbc/tallink";
	private static boolean isOpen = false;

	public static boolean isOpen() {
		return isOpen;
	}

	public static void open() throws SQLException {
		if (!isOpen) {
			Base.open(TLNK_DB_JNDI_NAME);
			isOpen = true;
			Base.connection().setAutoCommit(false);
		}
	}

	public static void close() {
		if (isOpen) {
			Base.rollbackTransaction();
			Base.close();
			isOpen = false;
		}
	}

	public static void commit() {
		Base.commitTransaction();
	}

	public static void rollback() {
		if (isOpen)
			Base.rollbackTransaction();
	}
	
	public static Connection connection() {
		return Base.connection();
	}
	public static CallableStatement prepareCall(String sql) throws SQLException {
		return Base.connection().prepareCall(sql);
	}

	@SuppressWarnings("rawtypes")
	public static MetaModel getMetaModel(Class<? extends Model> modelClass) {
        return Registry.instance().getMetaModel(modelClass);
    }

	
	public static <T extends Model> T findById(Class<? extends Model> modelClass, Object id) {
        if(id == null) return null;

        @SuppressWarnings("rawtypes")
        LazyList<T> l = null;
		MetaModel mm= getMetaModel(modelClass);
        return l.size() > 0 ? l.get(0) : null;
    }

	public static <T extends Model> T findByCode(Class<? extends Model> modelClass, String code) {
        if(code == null) return null;

        @SuppressWarnings("rawtypes")
		MetaModel mm = getMetaModel(modelClass);
        LazyList<T> l = new TLazyList<T>("code = ?", new Object[]{code}, mm).limit(1);
        return l.size() > 0 ? l.get(0) : null;
    }

	public static  <T extends Model> LazyList<T> findAll(Class<? extends Model> modelClass) {
        return new TLazyList<T>(null, new Object[]{}, getMetaModel(modelClass));
    }
	
	public static  <T extends Model> LazyList<T> find(Class<? extends Model> modelClass, String query, Object... params) {
        return new TLazyList<T>(query, params, getMetaModel(modelClass));
    }
	
	public static String getIdName(Class<? extends Model> modelClass) {
		return getMetaModel(modelClass).getIdName();
	}
	
	public static Object firstCell(String query, Object... params) {
		return Base.firstCell(query, params);
	}
	public static Long count(String query, Object... params) {
		return Convert.toLong(firstCell(query, params));
	}

}
